@file:JvmName("PermissionUtils")

package com.cmy.framework_utils

import android.app.Activity
import android.content.Context
import android.content.pm.PackageManager
import android.os.Build
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat

/**
 * Describe：
 * @author bsx
 * CreateTime：2019/12/9
 */


fun isGranted(context: Context, vararg permission: String): Boolean {
    if (!isMarshmallow()) {
        return true
    }
    permission.forEach {
        if (!isGranted(context, it)) {
            return false
        }
    }
    return true
}


fun isGranted(context: Context, permission: String): Boolean {
    return !isMarshmallow() || ContextCompat.checkSelfPermission(
        context,
        permission
    ) == PackageManager.PERMISSION_GRANTED
}


fun isMarshmallow(): Boolean {
    return Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
}

fun validatePermissions(permissions: Array<out String>) {
    if (permissions.isEmpty()) throw Exception("the permission can't be null")
}

fun filterNotDeniedPermissions(
    activity: Activity,
    permissions: Array<String>
): Array<out String> {
    val result = permissions.filter {
        !ActivityCompat.shouldShowRequestPermissionRationale(activity, it)
    }
    return result.toTypedArray()
}

fun filterNotDeniedPermissions(
    activity: Activity,
    permissions: List<String>
): Array<out String> {
    val result = permissions.filter {
        !ActivityCompat.shouldShowRequestPermissionRationale(activity, it)
    }
    return result.toTypedArray()
}